package com.sphere.freereader.impl;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

/**
 * Created by aquarius on 2016/9/4.
 */
public class ReaderImageCache implements ImageLoader.ImageCache {

    private LruCache<String, Bitmap> mMemoryCache;
    private static ReaderImageCache mImageCache;
    private static Object obj = new Object();

    private ReaderImageCache() {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            // 计算单个图片应该占有的大小 注意单位和缓存的单位要一致
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
    }


    public static ReaderImageCache getInstance() {
        if(mImageCache == null) {
            synchronized (obj) {
                if (mImageCache == null) {
                    mImageCache = new ReaderImageCache();
                }
            }
        }
        return mImageCache;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return mMemoryCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        mMemoryCache.put(url, bitmap);
    }
}
